import Mock from 'mockjs';
import { User, MatchRecord, InteractionRecord, DashboardStats, UserProfile, QueryUserprofileRequest } from '@/types';

// 配置Mock
Mock.setup({
  timeout: '200-600'
});

// 确保Mock在开发环境中工作
if (process.env.NODE_ENV === 'development') {
  console.log('开发环境Mock配置启动...');
}

// 生成随机头像
const getRandomAvatar = (gender: 'male' | 'female', index: number) => {
  return `https://api.dicebear.com/7.x/avataaars/svg?seed=${gender}${index}`;
};

// 生成随机城市
const cities = ['北京', '上海', '广州', '深圳', '杭州', '南京', '成都', '武汉', '西安', '重庆'];
const educations = ['高中', '大专', '本科', '硕士', '博士'];
const occupations = ['设计师', '工程师', '教师', '医生', '律师', '销售', '运营', '产品经理', '咨询师', '创业者'];
const tags = ['旅行', '美食', '运动', '读书', '电影', '音乐', '摄影', '健身', '瑜伽', '游戏', '科技', '文艺'];

// 生成用户数据
const generateUsers = (count: number): User[] => {
  const users: User[] = [];
  
  for (let i = 1; i <= count; i++) {
    const gender = Math.random() > 0.5 ? 'male' : 'female';
    const age = Mock.Random.integer(22, 45);
    const isVip = Math.random() > 0.7;
    
    users.push({
      id: String(i),
      nickname: Mock.Random.cname(),
      avatar: getRandomAvatar(gender, i),
      age,
      gender,
      education: Mock.Random.pick(educations),
      occupation: Mock.Random.pick(occupations),
      city: Mock.Random.pick(cities),
      height: gender === 'male' ? Mock.Random.integer(165, 185) : Mock.Random.integer(155, 175),
      income: Mock.Random.integer(5000, 50000),
      profileStatus: Mock.Random.pick(['pending', 'approved', 'rejected', 'incomplete']),
      registerTime: Mock.Random.datetime('yyyy-MM-dd HH:mm:ss'),
      lastLoginTime: Mock.Random.datetime('yyyy-MM-dd HH:mm:ss'),
      isVip,
      phone: Mock.Random.pick(['138', '139', '150', '151', '152']) + Mock.Random.string('number', 8),
      idCard: Mock.Random.string('number', 18),
      tags: Mock.Random.shuffle(tags).slice(0, Mock.Random.integer(2, 5)),
      introduction: Mock.Random.cparagraph(1, 3),
      requirements: Mock.Random.cparagraph(1, 2),
      photos: Array.from({ length: Mock.Random.integer(2, 6) }, (_, index) => 
        `https://picsum.photos/300/400?random=${i * 10 + index}`
      ),
    });
  }
  
  return users;
};

// 生成匹配记录
const generateMatchRecords = (userCount: number): MatchRecord[] => {
  const records: MatchRecord[] = [];
  
  for (let i = 1; i <= 50; i++) {
    const userAId = Mock.Random.integer(1, userCount);
    let userBId = Mock.Random.integer(1, userCount);
    
    // 确保不是同一个用户
    while (userBId === userAId) {
      userBId = Mock.Random.integer(1, userCount);
    }
    
    records.push({
      id: String(i),
      userA: {
        id: String(userAId),
        nickname: Mock.Random.cname(),
        avatar: getRandomAvatar(Math.random() > 0.5 ? 'male' : 'female', userAId),
        age: Mock.Random.integer(22, 45),
      },
      userB: {
        id: String(userBId),
        nickname: Mock.Random.cname(),
        avatar: getRandomAvatar(Math.random() > 0.5 ? 'male' : 'female', userBId),
        age: Mock.Random.integer(22, 45),
      },
      matchScore: Mock.Random.integer(60, 98),
      matchReason: Mock.Random.pick([
        '兴趣爱好相似',
        '年龄匹配度高',
        '地理位置接近',
        '教育背景相当',
        '职业互补',
        '价值观契合'
      ]),
      status: Mock.Random.pick(['pending', 'accepted', 'rejected', 'expired']),
      createTime: Mock.Random.datetime('yyyy-MM-dd HH:mm:ss'),
      counselor: Mock.Random.pick(['张顾问', '李顾问', '王顾问', '陈顾问']),
      notes: Mock.Random.sentence(5, 10),
    });
  }
  
  return records;
};

// 生成互动记录
const generateInteractionRecords = (): InteractionRecord[] => {
  const records: InteractionRecord[] = [];
  
  for (let i = 1; i <= 100; i++) {
    records.push({
      id: String(i),
      userA: String(Mock.Random.integer(1, 50)),
      userB: String(Mock.Random.integer(1, 50)),
      type: Mock.Random.pick(['chat', 'gift', 'meet']),
      content: Mock.Random.sentence(3, 8),
      timestamp: Mock.Random.datetime('yyyy-MM-dd HH:mm:ss'),
      status: Mock.Random.pick(['active', 'ended']),
    });
  }
  
  return records;
};

// 生成仪表板统计数据
const generateDashboardStats = (): DashboardStats => {
  return {
    todayNewUsers: Mock.Random.integer(80, 150),
    activeUsers: Mock.Random.integer(3000, 5000),
    pendingReviews: Mock.Random.integer(50, 120),
    todayMatches: Mock.Random.integer(30, 80),
    profileApprovalRate: Mock.Random.float(80, 95, 1, 1),
    matchResponseRate: Mock.Random.float(65, 85, 1, 1),
    paidConversionRate: Mock.Random.float(20, 35, 1, 1),
  };
};

// 生成用户档案数据
const generateUserProfiles = (count: number): UserProfile[] => {
  const profiles: UserProfile[] = [];
  const occupations = ['公务员', '教师', '医生', '护士', '律师', '法官', '警察', '工程师', '设计师', '销售'];
  const hometowns = ['安徽-宣城', '江苏-南京', '浙江-杭州', '广东-深圳', '北京', '上海', '四川-成都', '湖北-武汉'];
  const residences = ['北京', '上海', '广州', '深圳', '杭州', '南京', '成都', '武汉', '西安', '重庆'];
  const maritalStatuses = ['未婚', '离异', '丧偶'];
  const chineseZodiacs = ['鼠', '牛', '虎', '兔', '龙', '蛇', '马', '羊', '猴', '鸡', '狗', '猪'];
  const educations = ['高中', '大专', '本科', '硕士', '博士'];
  
  for (let i = 1; i <= count; i++) {
    const gender = Math.random() > 0.5 ? '男' : '女';
    const age = Mock.Random.integer(22, 45);
    const birthYear = new Date().getFullYear() - age;
    const birthMonth = Mock.Random.integer(1, 12);
    const birthDay = Mock.Random.integer(1, 28);
    const birthDate = `${birthYear}-${birthMonth.toString().padStart(2, '0')}-${birthDay.toString().padStart(2, '0')}`;
    const height = gender === '男' ? Mock.Random.integer(165, 185) : Mock.Random.integer(155, 175);
    const weight = Mock.Random.integer(90, 180);
    const bmi = (weight / 2) / Math.pow(height / 100, 2);
    
    let bmiDesc = '';
    if (bmi < 18.5) bmiDesc = '偏瘦';
    else if (bmi < 24) bmiDesc = '正常';
    else if (bmi < 28) bmiDesc = '偏胖';
    else bmiDesc = '肥胖';
    
    profiles.push({
      userNum: i,
      name: Mock.Random.cname(),
      gender,
      height,
      weight,
      bmiDesc,
      birthDate,
      age,
      chineseZodiac: Mock.Random.pick(chineseZodiacs),
      maritalStatus: Mock.Random.pick(maritalStatuses),
      occupation: Mock.Random.pick(occupations),
      hometown: Mock.Random.pick(hometowns),
      currentResidence: Mock.Random.pick(residences),
      education: Mock.Random.pick(educations),
      income: Mock.Random.integer(5000, 50000),
      parentsHasPension: Math.random() > 0.5,
    });
  }
  
  return profiles;
};

// 创建Mock数据
const mockUsers = generateUsers(100);
const mockUserProfiles = generateUserProfiles(100);
const mockMatchRecords = generateMatchRecords(100);
const mockInteractionRecords = generateInteractionRecords();
const mockDashboardStats = generateDashboardStats();

// API Mock 配置
Mock.mock('/api/auth/login', 'post', (options) => {
  const { account, password } = JSON.parse(options.body);
  
  if (account === 'admin' && password === '123456') {
    return {
      success: true,
      message: '登录成功',
      data: {
        user: {
          id: '1',
          username: '系统管理员',
          role: 'admin',
          permissions: ['*'],
          avatar: getRandomAvatar('male', 1),
          department: '技术部',
        },
        token: 'mock-jwt-token-admin',
      },
    };
  } else if (password === '123456') {
    return {
      success: true,
      message: '登录成功',
      data: {
        user: {
          id: '2',
          username: account,
          role: 'operator',
          permissions: ['user:read', 'user:write', 'match:read'],
          avatar: getRandomAvatar('female', 2),
          department: '运营部',
        },
        token: 'mock-jwt-token-operator',
      },
    };
  } else {
    return {
      success: false,
      message: '账号或密码错误',
      data: null,
    };
  }
});

// 用户档案查询API
Mock.mock('/api/matchmaking/userprofile/query', 'post', (options) => {
  console.log('Mock拦截到用户档案查询请求:', options);
  const requestData: QueryUserprofileRequest = JSON.parse(options.body);
  console.log('请求参数:', requestData);
  let filteredProfiles = [...mockUserProfiles];
  
  // 应用筛选条件
  if (requestData.userNumList && requestData.userNumList.length > 0) {
    filteredProfiles = filteredProfiles.filter(profile => 
      requestData.userNumList!.includes(profile.userNum)
    );
  }
  
  if (requestData.gender) {
    filteredProfiles = filteredProfiles.filter(profile => 
      profile.gender === requestData.gender
    );
  }
  
  if (requestData.ageRange) {
    if (requestData.ageRange.minAge) {
      filteredProfiles = filteredProfiles.filter(profile => 
        profile.age! >= requestData.ageRange!.minAge!
      );
    }
    if (requestData.ageRange.maxAge) {
      filteredProfiles = filteredProfiles.filter(profile => 
        profile.age! <= requestData.ageRange!.maxAge!
      );
    }
  }
  
  if (requestData.minHeight) {
    filteredProfiles = filteredProfiles.filter(profile => 
      profile.height >= requestData.minHeight!
    );
  }
  
  if (requestData.maxWeight) {
    filteredProfiles = filteredProfiles.filter(profile => 
      profile.weight <= requestData.maxWeight!
    );
  }
  
  if (requestData.educationRange) {
    // 学历等级映射
    const educationLevels = {
      '高中': 1,
      '大专': 2,
      '本科': 3,
      '硕士': 4,
      '博士': 5
    };
    
    if (requestData.educationRange.minEducation) {
      const minLevel = educationLevels[requestData.educationRange.minEducation as keyof typeof educationLevels] || 0;
      filteredProfiles = filteredProfiles.filter(profile => {
        const profileLevel = educationLevels[profile.education as keyof typeof educationLevels] || 0;
        return profileLevel >= minLevel;
      });
    }
    
    if (requestData.educationRange.maxEducation) {
      const maxLevel = educationLevels[requestData.educationRange.maxEducation as keyof typeof educationLevels] || 5;
      filteredProfiles = filteredProfiles.filter(profile => {
        const profileLevel = educationLevels[profile.education as keyof typeof educationLevels] || 0;
        return profileLevel <= maxLevel;
      });
    }
  }
  
  if (requestData.minIncome) {
    filteredProfiles = filteredProfiles.filter(profile => 
      (profile.income || 0) >= requestData.minIncome!
    );
  }
  
  if (requestData.occupation) {
    filteredProfiles = filteredProfiles.filter(profile => 
      profile.occupation.includes(requestData.occupation!)
    );
  }
  
  if (requestData.parentsHasPension !== undefined) {
    filteredProfiles = filteredProfiles.filter(profile => 
      profile.parentsHasPension === requestData.parentsHasPension
    );
  }
  
  const response = {
    code: 0,
    msg: '获取成功',
    data: {
      userprofileList: filteredProfiles,
      totalNum: filteredProfiles.length,
    },
  };
  console.log('Mock返回数据:', response);
  return response;
});

// 用户相关API (保留原有接口用于其他功能)
Mock.mock('/api/users', 'get', () => {
  return {
    success: true,
    message: '获取成功',
    data: {
      list: mockUsers.slice(0, 20),
      total: mockUsers.length,
      page: 1,
      pageSize: 20,
    },
  };
});

Mock.mock(/\/api\/users\/(\d+)/, 'get', (options) => {
  const id = options.url.match(/\/api\/users\/(\d+)/)?.[1];
  const user = mockUsers.find(u => u.id === id);
  
  return {
    success: true,
    message: '获取成功',
    data: user || null,
  };
});

// 仪表板统计API
Mock.mock('/api/dashboard/stats', 'get', () => {
  return {
    success: true,
    message: '获取成功',
    data: mockDashboardStats,
  };
});

// 匹配记录API
Mock.mock('/api/matches', 'get', () => {
  return {
    success: true,
    message: '获取成功',
    data: {
      list: mockMatchRecords.slice(0, 20),
      total: mockMatchRecords.length,
      page: 1,
      pageSize: 20,
    },
  };
});

// 互动记录API
Mock.mock('/api/interactions', 'get', () => {
  return {
    success: true,
    message: '获取成功',
    data: {
      list: mockInteractionRecords.slice(0, 20),
      total: mockInteractionRecords.length,
      page: 1,
      pageSize: 20,
    },
  };
});

// 审核相关API
Mock.mock('/api/reviews', 'get', () => {
  const pendingUsers = mockUsers.filter(u => u.profileStatus === 'pending').slice(0, 10);
  
  return {
    success: true,
    message: '获取成功',
    data: pendingUsers.map(user => ({
      id: Mock.Random.id(),
      user: {
        id: user.id,
        nickname: user.nickname,
        avatar: user.avatar,
        age: user.age,
        gender: user.gender,
      },
      submitTime: Mock.Random.datetime('yyyy-MM-dd HH:mm:ss'),
      type: Mock.Random.pick(['profile', 'photo', 'certification']),
      status: 'pending',
      content: user.introduction,
      photos: user.photos?.slice(0, 2),
    })),
  };
});

console.log('Mock API已配置完成');

export default Mock;